using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using Ubject = UnityEngine.Object;
using UnityEditorInternal;
using System.Linq;

public class UIViewCsScene : Editor
{
    public static Ubject main;
    public static UIModule group;
    public static ReorderableList selectedlist;

    static Color color    = new Color(0.5f, 0.5f, 0.5f, 0.5f);
    static int mainInstanceID = 0;
    static int instanceID = 0;
    static int seletID    = 0;

    static string field;
    static string[] coms;
    static Dictionary<string, Ubject> comDic = new Dictionary<string, Ubject>();

    static Rect rect;
    static Rect preview;
    static Rect control;

    static bool    isShow = false;
    static bool    isDrag = false;
    static Vector2 offect;
    static Vector2 viewSize;

    public static void Show(Ubject main)
    {
        group      = (UIModule)main;
        instanceID = group.transform.GetInstanceID();

        SceneView.duringSceneGui += OnSceneGUI;

        var view   = SceneView.lastActiveSceneView;

        var width  = 200;
        var height = 200;
        var x = view.position.width  - width  -5;
        var y = view.position.height - height +5;

        rect     = new Rect(x, y, width, height);
        viewSize = new Vector2(view.position.width, view.position.height);
        isShow   = true;
    }

    public static void Hide()
    {
        SceneView.duringSceneGui -= OnSceneGUI;
    }


  

    private static void OnSceneGUI(SceneView sceneView)
    {
        if (Selection.activeTransform != null && AnimatorEditorInspector.IsChild(Selection.activeTransform, instanceID) == false )
        {
            Hide();
            return;
        }


        Handles.BeginGUI();
        {
            var view = SceneView.lastActiveSceneView;

            if (view.position.size != viewSize)
            {
                rect.position += view.position.size - viewSize;
                viewSize = view.position.size;
            }

            rect = EditorGUICustom.OnDragGUI(rect, ref isDrag, ref offect, (r) =>
            {
                if (EditorGUICustom.ButtonTitle(r, $"{(isShow ? "v" : ">")} TypeGroup", TextAlignment.Left))
                {
                    isShow = !isShow;
                }
            });
        }
        Handles.EndGUI();


        if (isShow == false) return;

        GUILayout.BeginArea(rect);

        CheckDrop(ref main);

        EditorGUICustom.DrawBoxTitleColor("Preview", color, (r) =>
            {
                EditorGUICustom.BoxColor(Color.gray, (r) =>
                {
                    GUILayout.Space(5);
                    GUILayout.BeginHorizontal();
                    GUILayout.Space(5);
                    GUILayout.Label($"Field:", GUILayout.Width(60));
                    field = GUILayout.TextField(field, GUILayout.Width(rect.width - 80));
                    GUILayout.Space(5);
                    GUILayout.EndHorizontal();

                    GUILayout.BeginHorizontal();
                    GUILayout.Space(5);
                    GUILayout.Label($"Mian:", GUILayout.Width(60));
                    if (main == null)
                    {
                        EditorGUILayout.ObjectField(main, typeof(GameObject), true, GUILayout.Width(rect.width - 80));
                    }
                    else
                    {
                        EditorGUILayout.ObjectField(main, main.GetType(), true, GUILayout.Width((rect.width - 80)));
                    }

                    GUILayout.Space(5);
                    GUILayout.EndHorizontal();

                    GUILayout.BeginHorizontal();
                    GUILayout.Space(5);
                    GUILayout.Label($"Type:", GUILayout.Width(60));

                    if (main == null)
                    {
                        GUILayout.Label($"Null:", GUILayout.Width(80));
                    }
                    else
                    {
                        var temp = SelectComponent(rect);
                        if (temp.GetInstanceID() != main.GetInstanceID())
                        {
                            CheckMain(temp);
                        }
                        main = temp;
                    }
                    GUILayout.Space(5);
                    GUILayout.EndHorizontal();
                });
            });


        EditorGUICustom.DrawBoxTitleColor("Control", color, Control);


        GUILayout.EndArea();
 

        sceneView.Repaint();
    }
    private static void InitMain(Object main)
    {
        seletID = 0;

        comDic.Clear();
        comDic.Add("GameObject", main);
        var s_comps = new List<string>() { "GameObject" };

        Component[] m_coms;

        if (main is GameObject)
        {
            GameObject component = main as GameObject;
            m_coms               = component.GetComponents<Component>();
            mainInstanceID       = component.transform.GetInstanceID();
        }
        else
        {
           Component component = main as Component;
            m_coms             = component.GetComponents<Component>();
            mainInstanceID     = component.transform.GetInstanceID();
        }

        foreach (var item in m_coms)
        {
            var name = item.GetType().Name;
            s_comps  . Add(name);
            comDic   . Add(name, item);
        }



        coms = s_comps.ToArray();
    }

    private static  Ubject SelectComponent(Rect rect)
    {
        var popup = GUILayoutUtility.GetRect((rect.width ) , 20);
        popup.y += 1;
        popup.width = rect.width - 80;

        seletID = EditorGUI.Popup(popup, seletID, coms);

        return comDic[coms[seletID]];
    }




    private static void CheckDrop( ref Object main)
    {
        if (Selection.activeGameObject != null && Selection.activeTransform != null)
        {
            if (mainInstanceID != Selection.activeTransform.GetInstanceID())
            {
                main = Selection.activeObject;
                CheckMain(main);
                InitMain (main);
            }
        }
    }

    public static void CheckMain(Ubject ubject)
    {
        var mainID = ubject.GetInstanceID();
        var finds  = group.elements.Where(_ => _.main.GetInstanceID() == mainID);

        foreach (var item in finds)
        {
            main  = item.main;
            field = item.member;
        }

        if (finds.Count() <= 0 )
        {
            field = string.Empty;
        }
    }


    private static void Control(Rect rect)
    {
        if (GUILayout.Button("Add Emlenmt"))
        {
            if (string.IsNullOrEmpty(field) || main == null)
            {
                var tip = string.IsNullOrEmpty(field) ? "Field is null \n" : string.Empty;
                tip += main == null ? "Main is null \n" : string.Empty;
                EditorUtility.DisplayDialog("Error", tip, "OK");
                return;
            }

   
            if (group.elements == null)
                group.elements = new List<UIElement>();

            if (group.elements.Where(_ => _.member == field).FirstOrDefault() != null)
            {
                EditorUtility.DisplayDialog("Error", $"Field [{field}] is exist", "OK");
                return;
            }
            group.elements.Add(new UIElement() { member = field, main = main });
        }

       
    }
}
